<template>
    <div>
        <el-input v-model="queryData.clientName" placeholder="客户名称" size="small"></el-input>
        <el-input v-model="queryData.handoverUserName" placeholder="员工名称" size="small"></el-input>
        <el-date-picker
                v-model="queryData.joinTime"
                type="daterange"
                size="small"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
        </el-date-picker>&nbsp;&nbsp;
        <el-button type="primary" @click="queryDataHandle(1, 10)" size="small">查询</el-button>
<!--        <el-divider direction="vertical"></el-divider>-->
        <el-button type="primary" @click="resetQuery" size="small">重置</el-button>
        <div class="interspaceH"></div>
        <!--待分配客户-->
        <el-card class="box-card">
            <div slot="header" class="clearfix" style="display:flex;justify-content: space-between;align-items: center">
                <div>
                    <span style="font-size: 12px">共{{ multipleSelection.length }}个待分配客户</span>
                    <span style="color: #9d9d9d;font-size: 12px">上次同步时间{{ synchronizationTime }}</span>
                </div>
                <div style="float: right; padding: 3px 0">
                    <el-button type="primary" @click="assign()" size="small">分配客户</el-button>
                    <el-button plain size="small" @click="$emit('currentHandler', 'allocation')">分配记录</el-button>
                    <el-button plain size="small" @click="synchronization">同步</el-button>
                </div>
            </div>
            <div>
                <el-table :data="dataSource" style="width: 100%" @selection-change="rowChange"
                          :header-cell-style="{background:'#F3F4F7',color:'#555'}">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="clientName" label="客户昵称" :formatter="formatter"></el-table-column>
                    <el-table-column prop="handoverUserName" label="所属客服" :formatter="formatter"></el-table-column>
                    <el-table-column prop="clientRate" label="客户评分" :formatter="formatter"></el-table-column>
                    <el-table-column prop="joinTime" label="添加时间" :formatter="formatter"></el-table-column>
                    <el-table-column prop="dimissionTime" label="员工离职时间" :formatter="formatter"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button @click="detailHandle(scope.row)" type="text" size="small">详情</el-button>
                            <el-button type="text" size="small" disabled>聊天记录</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="interspaceH"></div>

                <el-pagination @size-change="queryDataHandle(pagePagination.currentPage,$event)"
                               @current-change="queryDataHandle($event,pagePagination.pageSize)"
                               :current-page="pagePagination.currentPage"
                               :page-sizes="pagePagination.pageSizes" :page-size="pagePagination.pageSize"
                               layout="total, sizes, prev, pager, next"
                               :total="pagePagination.total">
                </el-pagination>
            </div>
        </el-card>
        <!-- 分配客户 -->
        <el-dialog title="分配客户" :visible.sync="assignVisible" width="60%" :close-on-click-modal="false">
            <div class="tip" style="margin: 0 0 20px 0"><p>可将选中的客户转接给其他员工，进行后续服务<br>
                注意：90天内客户只能被转移一次，一个客户最多只能被转移两次</p></div>

            <ListSelect @getData="getData" :listFields="listFields" :dataSource="memberData"/>
            <span slot="footer" class="dialog-footer">
                    <el-button @click="assignVisible = false">取 消</el-button>
                <el-button type="primary" @click="assignVisible = false">确 定</el-button>
                </span>
        </el-dialog>

        <ClientDetail ref="clientDetail"/>
    </div>
</template>

<script>

import ClientDetail from '@/views/customer/client/client_detail'
import ListSelect from "@/components/list_select/list_select"

const queryData = {
    clientName: '',//客户名称
    handoverUserName: '',//员工名称
    joinTime: '',//员工离职日期
}
//多选框 - 开始

//多选框 - 结束
export default {
    name: "disclient",
    components: {
        ClientDetail,
        ListSelect
    },
    data() {
        return {
            tablePage: 0,
            synchronizationTime: "",
            multipleSelection: [],
            dictionary: {
            },
            fieldType: {
                dimissionTime: "datetime",
                joinTime: "datetime",
            },
            queryData: {...queryData},
            dataSource: [],
            assignVisible: false,
            clientForm: {},
            memberData: [],
            listFields: {
                deptName: "所属部门",
                empName: "员工名称",
            },
            pagePagination: {
                currentPage: 1,
                pageSizes: [10, 15, 20, 25],
                pageSize: 10,
                total: 0
            }
        }
    },
    mounted() {
        this.synchronizationTime = this.$moment(this.$t.data.scrm.asyncUnassignedClientTime).format("YYYY-MM-DD HH:mm:ss")
        this.queryDataHandle()
    },
    methods: {
        queryDataHandle(page = 1, row = 10) {
            let that = this;
            let queryData = {...this.queryData}

            if (queryData['joinTime'] != null && queryData['joinTime'] != "") {
                queryData['startJoinTime'] = queryData['joinTime'][0]
                queryData['endJoinTime'] = queryData['joinTime'][1]
                delete queryData['joinTime']
            }

            let payload = {
                ...queryData,
                unassignedType: "0",
                pageNum: page,
                pageSize: row
            }
            that.$request("/api/clientMigration/getMigrationsByParams/1_0", payload, "POST").then((data) => {
                this.dataSource = data.rows
                that.pagePagination['total'] = data.total
                that.pagePagination['pageSize'] = data.row
            })
        },
        resetQuery() {
            this.queryData = {...queryData}
        },
        rowChange(val) {
            this.multipleSelection = val;
        },
        formatter(row, column) {
            let field = column.property;
            let value = row[field];
            return this.$utils.formatterForLable(field, value, this.fieldType, this['dictionary'][field]);
        },
        synchronization() {
            this.$request("/api/clientMigration/asyncUnDispatch/1_0", {"page_id":0,"cursor":"","page_size":1000}, "POST").then((data) => {
                this.synchronizationTime = this.$moment().format("YYYY-MM-DD HH:mm:ss")
                this.$t.data.scrm.asyncUnassignedClientTime = this.synchronizationTime
                this.$message.success("同步成功")
                this.queryDataHandle()
            })
        },
        detailHandle(row) {
            this.$refs.clientDetail.open(true, row)
        },
        assign() {
            let that = this

            if (!that.multipleSelection.length > 0) {
                that.$message.error("未选择客户")
                return
            }

            that.$request("/api/emp/getAllEmp/1_0", {}, "POST").then((data) => {
                that.memberData = data.rows
                that.assignVisible = true
            })
        },
        async getData(data) {
            let clients = this.multipleSelection

            let dictionary = {}

            clients.map((item) => {
                if (dictionary[item.handoverUserid] == null) {
                    dictionary[item.handoverUserid] = {
                        handover_userid: item.handoverUserid,
                        takeover_userid: data.empId,
                        external_userid: [item.externalUserid]
                    }
                } else {
                    dictionary[item.handoverUserid]['external_userid'].push(item.externalUserid)
                }
            })

            for (let key in dictionary) {
                let requestJson = JSON.stringify(dictionary[key])
                let payload = {
                    requestJson: JSON.stringify(dictionary[key]),
                    requestBody: dictionary[key],
                    clients
                }

                await this.$request("/api/clientMigration/transferCustomer/1_0", payload, "POST")
            }
            this.queryDataHandle()
            this.assignVisible = false
            this.$message.success("分配成功")
        },
    }
}
</script>

<style scoped>
.el-tab-pane .el-input {
    width: 150px;
}

.el-form-item__content .el-input {
    width: 100%;
}

.dialog-footer {
    text-align: right;
}
</style>
